/*
@author Anthony Victorio
@date 10/25/2011
@description Controller for the universal comment controller.
Requires that the object have "Allow Activities" enabled
*/

public with sharing class MM_CommentController {
	
	//parentID is assigned to controller from the component
	public string parentID {get;set;}
	
	//object for every new note that's inserted
	public Note newNote {get;set;}
	
	public MM_CommentController() {
		//initialize the new note
		newNote = new Note();
	}
	
	//saves the note
	public PageReference saveNote() {
		//assigns parent id, must be done at this point
		//will not be recognized prior to component being load
		newNote.ParentId = parentID;
		//since we're only capturing the note body, the note
		//title will contain a truncated version of the body
		//title is a quired field.
		if(newNote.Body != null) {
			//in order to avoid out of bound error
			//first we ensure that body is greater than 40 characters
			//only then do we truncate
			if(newNote.Body.length() > 40) {
				newNote.Title = newNote.Body.substring(0,40);
			} 
			//if less than 40 charatercs, no need to truncate
			else {
				newNote.Title = newNote.Body;
			}
		}
		
		//insert the note
		insert newNote;
		
		//initiate object for new note
		newNote = new Note();
		return null;
	}
	
	//retrieves a list of old notes associated with the parent ID
	//sorted by Created Date in descending order
	public Note[] getOldNotes() {
		return [select Id, CreatedDate, CreatedBy.Name, Title, Body 
		from Note where ParentId = :parentID order by CreatedDate desc];
	}

}